package com.jc.oms.controller.returnProduct;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.MD5;
import com.jc.common.util.WebUtils;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderReturn;
import com.jc.oms.controller.BaseController;
import com.jc.service.order.XorderService;
import com.jc.service.xorderreturn.XorderReturnService;
import com.jc.service.yxreturnorder.YXReturnOrderService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@SuppressWarnings("all")
@Controller
@RequestMapping("returnOrder")
public class ReturnOrderController extends BaseController {

    @Autowired
    private YXReturnOrderService yxReturnOrderService;
    @Autowired
    private XorderReturnService xorderReturnService;
    @Autowired
    private XorderService xorderService;


    /**
     * 发起售后申请
     * */
    @RequestMapping(value = "/updateReturnPro" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateReturnPro(HttpServletRequest request){
       Map<String,Object> resultMap =  new HashMap<String,Object>(){{
           System.out.println("===============");
           put("code",10000);
           put("data",null);
       }};
        Map<String, Object> param;
       try{
           param = WebUtils.ReadAsChars(request);
           if (param.get("reason") == null || param.get("reasonDesc") == null){
               throw new BaseServiceException("必传参数为空");
           }
           if (param.get("channelOrderId") == null){
               throw new BaseServiceException("必传参数为空");
           }
           resultMap = yxReturnOrderService.updateReturnPro(param);
       }catch (Exception e){
           getLoger().error("发起退货申请出错!!!!!"+e.getLocalizedMessage());
           resultMap.put("code",9999);
           resultMap.put("msg",e.getLocalizedMessage());
          e.printStackTrace();
       }
        return resultMap;
    }

    /**
     * 绑定物流单号
     * */
    @RequestMapping(value = "/bindingLogisticsNumber" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> bindingLogisticsNumber(HttpServletRequest request){
        Map<String,Object> resultMap =  new HashMap<String,Object>(){{
            put("code",10000);
            put("data",null);
        }};
        Map<String, Object> param;
        try{
            param = WebUtils.ReadAsChars(request);
            //订单Id
            if (param.get("channelOrderId") == null || param.get("expressInfo") == null){
                throw new BaseServiceException("必传参数为空!");
            }
            Boolean aBoolean = yxReturnOrderService.bindingLogisticsNumber(param);
            if (!aBoolean){
                throw new BaseServiceException("服务器异常!!!");
            }
            resultMap.put("data","SUCCESS");
        }catch (Exception e){
            getLoger().error("绑定物流单号出错!!!!!"+e.getLocalizedMessage());
            resultMap.put("code",9999);
            resultMap.put("msg",e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    /***
     *确认收货
     * */
    @RequestMapping(value = "/confirmReceipt" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> confirmReceipt(HttpServletRequest request){
        Map<String,Object> resultMap =  new HashMap<String,Object>(){{
            put("code",10000);
            put("data",null);
        }};
        Map<String, Object> param;
        try{
            param = WebUtils.ReadAsChars(request);
            //订单Id
            if (param.get("channelSource") == null || param.get("channelOrderIds") == null){
                throw new BaseServiceException("必传参数为空!");
            }
            //
            Boolean aBoolean = yxReturnOrderService.confirmReceipt(param);
            if (!aBoolean){
                throw new BaseServiceException("服务器异常!!!");
            }
            resultMap.put("data","SUCCESS");
        }catch (Exception e){
            getLoger().error("确认收货出错!!!!!"+e.getLocalizedMessage());
            resultMap.put("code",9999);
            resultMap.put("msg",e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    /***
     *确认收货
     * */
    @RequestMapping(value = "/cancelAftersale" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> cancelAftersale(HttpServletRequest request){
        Map<String,Object> resultMap =  new HashMap<String,Object>(){{
            put("code",10000);
            put("data",null);
        }};
        Map<String, Object> param;
        try{
            param = WebUtils.ReadAsChars(request);
            //订单Id
            if (param.get("channelOrderId") == null){
                throw new BaseServiceException("必传参数为空!");
            }
            String channelOrderId = param.get("channelOrderId").toString();
            List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
                setChannelOrderId(channelOrderId);
            }});
            if (CollectionUtils.isEmpty(xorders)){
                throw new BaseServiceException("当前订单不存在!!! 渠道Id" + channelOrderId);
            }
            Xorder xorder = xorders.get(0);
            List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
                setOrderId(xorder.getId());
            }});
            if (CollectionUtils.isEmpty(xorderReturns)){
                throw new BaseServiceException("当前订单申请单不存在! 渠道Id" + channelOrderId);
            }
            XorderReturn xorderReturn = xorderReturns.get(0);
            if (xorderReturn.getReturnFromId() == null){
                throw new BaseServiceException("该申请单没有售后Id 申请单Id"+xorderReturn.getId());
            }
           resultMap = yxReturnOrderService.cancelAftersale(xorderReturn.getReturnFromId());
        }catch (Exception e){
            getLoger().error("确认收货出错!!!!!"+e.getLocalizedMessage());
            resultMap.put("code",9999);
            resultMap.put("msg",e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }




    /**
     * 退货回调
     * */
    @RequestMapping(value = "/addressCallBack", method = RequestMethod.POST)
    public String addressCallBack(HttpServletRequest request) throws Exception {
        Map<String, Object> stringObjectMap = WebUtils.ReadAsChars(request);
        String baseUrl = "http://openapi-test.you.163.com/mock/api/v1/callbackRefundAddress";
        LinkedHashMap map = new LinkedHashMap<String,String>();
        String date = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        map.put("method","/callbackRefundAddress");
        map.put("appKey","0dc258e4e9004ba79109d1afcb8df8ef");
        map.put("applyId",stringObjectMap.get("applyId"));
        map.put("type",stringObjectMap.get("type"));
        LinkedHashMap sign = getSign(map);
        System.out.println(map);
        String s = HttpUtil.post(baseUrl,sign);
        System.out.println(s);
        return s;
    }

    /**
     * 触发包裹物流绑单回调
     * */
    @RequestMapping(value = "/logisticsTieback", method = RequestMethod.POST)
    public String logisticsTieback(HttpServletRequest request) throws Exception {
        Map<String, Object> stringObjectMap = WebUtils.ReadAsChars(request);
        String baseUrl = "http://openapi-test.you.163.com/mock/api/v1/callbackDeliveryOrder";
        LinkedHashMap map = new LinkedHashMap<String,String>();
        String date = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        map.put("method","/callbackDeliveryOrder");
        map.put("appKey","0dc258e4e9004ba79109d1afcb8df8ef");
        map.put("orderId",stringObjectMap.get("orderId"));
        LinkedHashMap sign = getSign(map);
        System.out.println(map);
        String s = HttpUtil.post(baseUrl,sign);
        System.out.println(s);
        return s;
    }

    /**
     * 严选拒绝退货回调
     * */
    @RequestMapping(value = "/refuseReturnCallback", method = RequestMethod.POST)
    public String refuseReturnCallback(HttpServletRequest request) throws Exception {
        Map<String, Object> stringObjectMap = WebUtils.ReadAsChars(request);
        String baseUrl = "http://openapi-test.you.163.com/mock/api/v1/callbackRefundReject";
        LinkedHashMap map = new LinkedHashMap<String,String>();
        String date = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        map.put("method","/callbackRefundReject");
        map.put("appKey","0dc258e4e9004ba79109d1afcb8df8ef");
        map.put("applyId",stringObjectMap.get("applyId"));
        LinkedHashMap sign = getSign(map);
        System.out.println(map);
        String s = HttpUtil.post(baseUrl,sign);
        System.out.println(s);
        return s;
    }

    /**
     * 退货包裹确认收货回调
     * */
    @RequestMapping(value = "/returnPackageConfirmReceipt", method = RequestMethod.POST)
    public String returnPackageConfirmReceipt(HttpServletRequest request) throws Exception {
        Map<String, Object> stringObjectMap = WebUtils.ReadAsChars(request);
        String baseUrl = "http://openapi-test.you.163.com/mock/api/v1/callbackRefundExpressConfirm";
        LinkedHashMap map = new LinkedHashMap<String,String>();
        String date = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        map.put("method","/callbackRefundExpressConfirm");
        map.put("appKey","0dc258e4e9004ba79109d1afcb8df8ef");
        map.put("applyId",stringObjectMap.get("applyId"));
        LinkedHashMap sign = getSign(map);
        System.out.println(map);
        String s = HttpUtil.post(baseUrl,sign);
        System.out.println(s);
        return s;
    }

    /**
     * 触发严选系统取消退货回调
     * */
    @RequestMapping(value = "/cancelReturnCallback", method = RequestMethod.POST)
    public String cancelReturnCallback(HttpServletRequest request) throws Exception {
        Map<String, Object> stringObjectMap = WebUtils.ReadAsChars(request);
        String baseUrl = "http://openapi-test.you.163.com/mock/api/v1/callbackRefundSystemCancel";
        LinkedHashMap map = new LinkedHashMap<String,String>();
        String date = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        map.put("method","/callbackRefundSystemCancel");
        map.put("appKey","0dc258e4e9004ba79109d1afcb8df8ef");
        map.put("applyId",stringObjectMap.get("applyId"));
        LinkedHashMap sign = getSign(map);
        System.out.println(map);
        String s = HttpUtil.post(baseUrl,sign);
        System.out.println(s);
        return s;
    }


    public static LinkedHashMap<String,Object> getSign(LinkedHashMap<String, Object> map) {
        String appKey = "0dc258e4e9004ba79109d1afcb8df8ef";
        String appSecret = "97ee365ac83e46819a5ecc54f7568185";
        String timestamp = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        timestamp = DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT);
        if(map == null || map.get("method") == null || StringUtils.isBlank(map.get("method").toString())) {
            throw new BaseServiceException("获取网易严选API签名,必须传入 method");
        }
        map.put("appKey", appKey);
        map.put("timestamp", timestamp);
        //这里将map.entrySet()转换成list
        List<Map.Entry<String,Object>> list = new ArrayList<Map.Entry<String,Object>>(map.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String,Object>>() {
            //升序排序
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        StringBuffer buffer = new StringBuffer();
        buffer.append(appSecret);
        if(list != null && list.size() > 0) {
            for(Map.Entry<String,Object> entry : list){
                buffer.append(entry.getKey() + "=" + entry.getValue());
            }
        }

        buffer.append(appSecret);
        System.out.println("加密前字符串" + buffer.toString());
        map.put("sign", MD5.md5(buffer.toString()));
        System.out.println("加密后字符串" + MD5.md5(buffer.toString()));
        return map;
    }

}
